package com.module.base.widget.pager;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.module.base.utils.CollectionUtil;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * author: yanxuwen
 * createDate: 2022/11/1 14:29
 * Description :
 */
public class MyFragmentAdapter extends FragmentStateAdapter {
    private List<? extends Fragment> fragmentList;
    private List<Long> fragmentIds = new ArrayList<>();//用于存储更新fragment的特定标识
    private HashSet<Long> creatIds = new HashSet<>();//得用hashset防重，用于存储adapter内的顺序
    private boolean isLoop;
    private FragmentActivity fragmentActivity;
    private Fragment fragment;

    public MyFragmentAdapter(@NonNull FragmentActivity fragmentActivity, List<? extends Fragment> fragments) {
        this(fragmentActivity, fragments, false);
    }

    public MyFragmentAdapter(@NonNull FragmentActivity fragmentActivity, List<? extends Fragment> fragments, boolean isLoop) {
        super(fragmentActivity);
        update(fragments);
        this.isLoop = isLoop;
        this.fragmentActivity = fragmentActivity;
    }

    public MyFragmentAdapter(@NonNull Fragment fragment, List<? extends Fragment> fragments) {
        super(fragment);
        update(fragments);
        this.fragment = fragment;
    }

    public void update(List<? extends Fragment> fragmentLists) {
        long tag = System.currentTimeMillis();//避免刷新重复，导致无法数据变更不了
        this.fragmentList = fragmentLists;
        fragmentIds.clear();
        if (fragmentLists != null) {
            for (int i = 0; i < fragmentLists.size(); i++) {
                fragmentIds.add(Long.parseLong(String.valueOf(tag + i)));
            }
        }
        notifyDataSetChanged();
    }


    @NonNull
    @Override
    public Fragment createFragment(int position) {
        Long ids = fragmentIds.get(position % fragmentList.size());
        creatIds.add(ids);//创建的时候将未添加的fragment添加进来，每次刷新都会调用这里，其次调用containsItem
        if (position >= 0 && !CollectionUtil.isEmptyOrNull(fragmentList))
            return fragmentList.get(position % fragmentList.size());
        else
            return null;
    }

    public Fragment getFragment(int position) {
        if (position >= 0 && !CollectionUtil.isEmptyOrNull(fragmentList))
            return fragmentList.get(position % fragmentList.size());
        else
            return null;
    }

    @Override
    public int getItemCount() {
        if (CollectionUtil.isEmptyOrNull(fragmentList)) {
            return 0;
        }
        if (fragmentList.size() == 1) {
            return 1;
        }
        return isLoop ? Integer.MAX_VALUE : fragmentList.size();
    }

    /**
     * 这两个方法必须重写，作为数据改变刷新检测的工具
     *
     * @param position
     * @return
     */
    @Override
    public long getItemId(int position) {
        return fragmentIds.get(position % fragmentList.size());
    }

    @Override
    public boolean containsItem(long itemId) {
        return creatIds.contains(itemId);
    }

    public int getFirstPosition() {
        try {
            return (getItemCount() / fragmentList.size() / 2) * fragmentList.size();
        } catch (Exception e) {
            return 0;
        }
    }

    public void destroy() {
        //清除所有
        FragmentManager fm = null;
        if (fragmentActivity != null) {
            fm = fragmentActivity.getSupportFragmentManager();
        } else if (fragment != null) {
            fm = fragment.getChildFragmentManager();
        }
        if (fm != null) {
            for (Fragment frag : fragmentList) {
                if (frag == null) {
                    continue;
                }
                try {
                    fm.beginTransaction().remove(frag).commit();
                    fm.popBackStack();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        fragmentList.clear();
        fragmentIds.clear();
        creatIds.clear();
        fragmentActivity = null;
        fragment = null;
    }
}